package cn.echo.ecc.service.impl;

import cn.echo.ecc.domain.PayFlow;
import cn.echo.ecc.domain.PayOrder;
import cn.echo.ecc.dto.PayApplyNotifyTxParamDto;
import cn.echo.ecc.enums.GlobalExceptionCode;
import cn.echo.ecc.mapper.PayOrderMapper;
import cn.echo.ecc.service.IPayFlowService;
import cn.echo.ecc.service.IPayOrderService;
import cn.echo.ecc.util.AssertUtil;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.smartcardio.SunPCSC;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulan
 * @since 2022-10-15
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private IPayFlowService payFlowService;

    @Override
    public PayOrder selectByOrderNo(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }

    /**
     * 修改支付单状态和新增支付流水
     * @param payApplyNotifyTxParamDto
     */
    @Override
    public void savePayOrderAndPayFlow(PayApplyNotifyTxParamDto payApplyNotifyTxParamDto) {
        PayOrder payOrder = payApplyNotifyTxParamDto.getPayOrder();
        PayFlow payFlow = payApplyNotifyTxParamDto.getPayFlow();
        String orderNo = payOrder.getOrderNo();
        PayOrder payOrderTem = selectByOrderNo(orderNo);
        AssertUtil.isNotNull(payOrderTem, GlobalExceptionCode.PAY_ORDER_NOT_EXIST_ERROR);
        synchronized (orderNo) {
            if (payOrderTem.getPayStatus().equals(PayOrder.WAIT_PAY_STATUS)) {
                updateById(payOrder);
                payFlowService.insert(payFlow);
            }
        }
    }

    /**
     * 订单超时取消，修改支付单状态
     * @param orderNo
     */
    @Override
    public void cancelPayOrder(String orderNo) {
        AssertUtil.isNotEmpty(orderNo,GlobalExceptionCode.PARAM_IS_NOT_BULL);
        PayOrder payOrder = selectByOrderNo(orderNo);
        if (payOrder != null && payOrder.getPayStatus() == PayOrder.WAIT_PAY_STATUS) {
            // 1.修改支付单状态
            payOrder.setUpdateTime(new Date());
            payOrder.setPayStatus(PayOrder.CANCEL_STATUS);
            updateById(payOrder);
            // 2.通知支付宝关闭订单
            try {
                Factory.Payment.Common().close(orderNo);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("关闭订单失败，订单：{}",orderNo);
            }
        }
    }
}
